package com.youxin.chat.pay.mq.consumer;


import com.youxin.common.constant.MqConstant;
import com.youxin.chat.pay.config.PayProperties;
import com.youxin.chat.pay.mapper.CommonOrderMapper;
import com.youxin.chat.pay.mapper.RedSendMapper;
import com.youxin.chat.pay.model.RedSend;
import com.youxin.chat.pay.service.SequenceService;
import com.youxin.chat.pay.service.TemplateService;
import com.youxin.chat.pay.service.manager.ImManager;
import com.youxin.chat.pay.service.manager.RedPackManager;
import com.youxin.chat.pay.service.rpc.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedPackExpireConsumer {

    private Logger logger = LoggerFactory.getLogger(RedPackExpireConsumer.class);

    @Resource
    private RedSendMapper redSendMapper;

    @Resource
    private SequenceService sequenceService;

    @Resource
    private CommonOrderMapper commonOrderMapper;

    @Resource
    private ImManager imManager;

    @Resource
    private PayProperties payProperties;

    @Resource
    private RedPackManager redPackManager;

    @Resource
    private UserService userService;

    @Resource
    private TemplateService templateService;

    @RabbitListener(queues = MqConstant.RED_PACK_TIMEOUT_PROCESS_QUEUE_NAME)
    @RabbitHandler
    public void get(String data) {
        logger.info("收到红包过期消息,data={}", data);
        String id = data;
        RedSend redSend = redSendMapper.selectById(id);
        if (redSend == null) {
            logger.error("红包找不到，id={}", id);
            return;
        }
        if (redSend.getRedStatus() == 1) {
            logger.info("红包领取完成");
            return;
        }
        try {
            String refundOrderNo = sequenceService.buildThirdOrderNo("RE");
            int count = redPackManager.doExpire(redSend, refundOrderNo);
            if (count < 1) {
                return;
            }
           templateService.sendRedPackExpireMessage(refundOrderNo);
        } catch (Exception e) {
            logger.error("红包过期通知处理失败，data={},error=", data, e);
        }
    }
}
